<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input v-model="formData.deviceCode" placeholder="请输入设备编号" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="formData.deviceName" placeholder="请输入设备名称" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备品牌" prop="deviceBrand">
              <el-input v-model="formData.deviceBrand" placeholder="请输入设备品牌" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptList" :normalizer="normalizer" 
                          placeholder="选择所属部门" style="width: 100%" @select="handleDeptSelect" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属工序id" prop="processId">
              <el-input v-model="formData.processId" placeholder="请输入所属工序id" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属工序名称" prop="processName">
              <el-input v-model="formData.processName" placeholder="请输入所属工序名称" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="iot关联id" prop="iotDeviceId">
              <el-input v-model="formData.iotDeviceId" placeholder="请输入iot关联id" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" 
                         :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序字段" prop="sort">
              <el-input v-model="formData.sort" placeholder="请输入排序字段" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as DeviceApi from '@/api/system/device';
import { getDictDatas, DICT_TYPE } from '@/utils/dict';
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "DeviceForm",
  components: {
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 部门列表
      deptList: [],
      // 表单参数
      formData: {
        id: undefined,
        deviceCode: undefined,
        deviceName: undefined,
        deviceBrand: undefined,
        deptId: undefined,
        deptName: undefined,
        processId: undefined,
        processName: undefined,
        iotDeviceId: undefined,
        status: 1, // 默认开启状态
        sort: undefined,
      },
      // 表单校验
      formRules: {
        deviceCode: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
        deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
        deptId: [{ required: true, message: '所属部门不能为空', trigger: 'change' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
        sort: [{ required: true, message: '排序字段不能为空', trigger: 'blur' }],
      },
    };
  },
  created() {
    this.getDeptList();
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await DeviceApi.getDevice(id);
          this.formData = res.data;
          this.dialogTitle = "编辑设备";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增设备";
      }
    },

    /** 获取部门列表 */
    getDeptList() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, "id")[0]?.children || [];
      });
    },

    /** 部门选择处理 */
    handleDeptSelect(node) {
      this.formData.deptName = node?.name || '';
    },

    /** 处理树形数据 */
    handleTree(data, id, parentId, children, rootId) {
      id = id || 'id';
      parentId = parentId || 'parentId';
      children = children || 'children';
      rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] || 0 })) || 0;
      // 对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data));
      // 循环所有项
      const treeData = cloneData.filter(father => {
        const branchArr = cloneData.filter(child => {
          // 返回每一项的子级数组
          return father[id] === child[parentId];
        });
        branchArr.length > 0 ? father[children] = branchArr : delete father[children];
        // 返回第一层
        return father[parentId] === rootId;
      });
      return treeData.length > 0 ? treeData : cloneData;
    },

    /** 部门节点格式化 */
    normalizer(node) {
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children,
      };
      if (node.deptType == 3) {
        normalizedNode.isDisabled = true;
      }
      return normalizedNode;
    },

    /** 获取字典数据 */
    getDictDatas(dictType) {
      return this.$store.getters.dict_datas[dictType] || [];
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await DeviceApi.updateDevice(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await DeviceApi.createDevice(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        deviceCode: undefined,
        deviceName: undefined,
        deviceBrand: undefined,
        deptId: undefined,
        deptName: undefined,
        processId: undefined,
        processName: undefined,
        iotDeviceId: undefined,
        status: 1, // 默认开启状态
        sort: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
